var express = require('express');
var router = express.Router();
const UniSMS = require('unisms').default
var { videoModel, loginModel, thumbs_upModel, commentModel, collectionModel,followsModel } = require('../../../model/model');


// token key值
var { ACCESS_KEY, REFRESH_KEY } = require('../../API/token_keys/keys')

// 封装创建，验证token
var { generateToken, verifyToken } = require('../../API/generate_token/generateToken')
// token验证 中间件导入
var { short_checkAuth, length_checkAuth } = require('../../API/verify_token/verify_Token')



// 双token登录
router.post('/login', async (req, res) => {
  let userdata = req.body
  let data = await loginModel.find({ tel: userdata.tel, password: userdata.password })
  if (data.length > 0) {
    let payload = {
      _id: data[0]._id,
      name: data[0].name,
    }
    //   //生成token
    let access_token = generateToken(payload, ACCESS_KEY, '1h')
    let REFRESH_token = generateToken(payload, REFRESH_KEY, 60 * 60 * 24 * 7)

    res.send({
      code: 200,
      msg: '登录成功',
      _id: data[0]._id,
      data: {
        access_token,
        REFRESH_token
      }
    })
  } else {
    res.send({
      code: 400,
      msg: '登录失败,账号或密码错误'
    })
  }
})


// 获取验证码,向手机发送短信，获取验证码
router.get('/getyzm', async (req, res) => {
  const client = new UniSMS({
    accessKeyId: 'PYqSuZEnwZjnsxvoXFhYRWsi59ZARzufsKDk8U4D7mvGret3X',
    accessKeySecret: 'NRz14j3Yz7v6xX8djJoJNoW6N9nLDN', //当你实名认证之后就会自动生成ID，直接复制就行
  })
  const bind_contact = req.query.tel
  //生成随机的四位数验证码，也可以修改成其他几位数验证码
  const len = Math.floor(1000 + Math.random() * 9000)
  //  发送短信
  client.send({
    to: bind_contact,
    signature: '董起嘉',
    templateId: 'pub_verif_basic', //短信报备中模板管理，在里面随便复制一个通道就可以
    templateData: {
      code: len,
    },
  }).then(ret => {
    res.send({ code: ret.code, len: len })
  }).catch(err => {
    console.log(err);
  })
})


// 注册账号
router.post('/register', async (req, res) => {
  const userdata = req.body
  const data = await loginModel.findOne({ tel: userdata.tel })
  if (data) {
    res.send({
      code: 400,
      msg: '该手机号已注册'
    })
  } else {
    // 随机数
    let aa = 'QWERTYUIOPASDFGHJKLZXCVBNM1234567890qwertyuiopasdfghjklzxcvbnm'
    let name = '视刻游客'
    for (let i = 0; i < 6; i++) {
      const random = Math.floor(Math.random() * aa.length)
      name += aa[random]
    }
    await loginModel.create({ tel: userdata.tel,
       password: userdata.password, 
       name: name,
       my_fensi:0,
       my_guanzhu:0,
       my_desc: '这个人很懒，什么都没有留下',
       image:'https://pic.616pic.com/ys_img/00/05/09/8LfaQcDrWd.jpg',
    })
    res.send({
      code: 200,
      msg: '注册成功'
    })
  }
})

// 重置密码
router.post('/resetpassword', async (req, res) => {
  let data = req.body
  let user = await loginModel.findOne({ tel: data.tel })
  console.log(user.password == data.password);

  if (user.password == data.password) {
    res.send({
      code: 400,
      msg: '密码不能与原密码相同'
    })
  } else {
    await loginModel.updateOne({ tel: data.tel }, { password: data.password })
    res.send({
      code: 200,
      msg: '修改成功'
    })
  }
})

// 视频上传存数据库
router.post('/add_video', short_checkAuth(ACCESS_KEY), async (req, res) => {
  let data = req.body
  console.log(data);
  let claim = req.claim
  data.user_id = claim._id //用户id
  data.video_state = false //视频状态
  data.video_thumbs_up = 0 //点赞数
  data.video_collection = 0 //收藏数
  await videoModel.create(data)
  res.send({
    code: 200,
    msg: '上传成功'
  })
})

// 视频获取
router.get('/get_video', short_checkAuth(ACCESS_KEY), async (req, res) => {
  let video = await videoModel.find().populate('user_id').lean()
  let thumbs_up = await thumbs_upModel.find().lean()
  let collection = await collectionModel.find().lean()
  video.forEach(item => {
    if (!item.dianzan && !item.shoucang) {
      item.dianzan = []
      item.shoucang = []
    }
    video.forEach(item => {
      item.dianzan = thumbs_up.filter(i => i.video_id.toString() == item._id.toString())
      item.shoucang = collection.filter(e => e.video_id.toString() == item._id.toString())
    })
  })
  res.send({
    code: 200,
    data: video
  })
})
// 获取关注的视频
router.get('/get_guanzhu_video', short_checkAuth(ACCESS_KEY), async (req, res) => {
  let _id = req.claim._id
  let guanzhu = await followsModel.find({user_id:_id})
  console.log(guanzhu);
  
  let video = await videoModel.find({user_id:{$in:guanzhu.map(item=>item.followed_id)}}).populate('user_id').lean()
  console.log(video);
  
  res.send({
    code: 200,
    data: video
  })
})


// 点赞
router.post('/post_dianzan', short_checkAuth(ACCESS_KEY), async (req, res) => {
  let data = req.body
  let user_id = req.claim._id
  let dianzan = await thumbs_upModel.findOne({ user_id: user_id, video_id: data._id })
  if (dianzan) {
    if(dianzan.thumbs_up_state) {
      await thumbs_upModel.updateOne({ user_id: user_id, video_id: data._id }, { thumbs_up_state: false })
      let video = await videoModel.findOne({ _id: data._id })
      console.log(video);
      
      await videoModel.updateOne({_id:video._id},{video_thumbs_up:video.video_thumbs_up-1})
      res.send({
        code: 200,
        msg: '取消点赞成功'
      })
    }else{
      await thumbs_upModel.updateOne({ user_id: user_id, video_id: data._id }, { thumbs_up_state: true })
      let video = await videoModel.findOne({ _id: data._id })
      await videoModel.updateOne({_id:video._id},{video_thumbs_up:video.video_thumbs_up+1})
      res.send({
        code: 200,
        msg: '点赞成功'
      })
    }
    
  } else {
    await thumbs_upModel.create({ user_id: user_id, video_id: data._id, thumbs_up_state: true, collection_state: false })
    let video = await videoModel.findOne({ _id: data._id })
    await videoModel.updateOne({_id:video._id},{video_thumbs_up:video.video_thumbs_up+1})
    res.send({
      code: 200,
      msg: '点赞成功'
    })
  }
})


// 收藏
router.post('/post_shoucang', short_checkAuth(ACCESS_KEY), async (req, res) => {
  let data = req.body
  let user_id = req.claim._id
  let shoucang = await collectionModel.findOne({ user_id: user_id, video_id: data._id })
  if (shoucang) {
    if(shoucang.collection_state) {
      await collectionModel.updateOne({ user_id: user_id, video_id: data._id }, {collection_state: false })
      let video = await videoModel.findOne({ _id: data._id })
      await videoModel.updateOne({_id:video._id},{video_collection:video.video_collection-1})
      res.send({
        code: 200,
        msg: '取消收藏成功'
      })
    }else{
      await collectionModel.updateOne({ user_id: user_id, video_id: data._id }, {collection_state: true })
      let video = await videoModel.findOne({ _id: data._id })
      await videoModel.updateOne({_id:video._id},{video_collection:video.video_collection+1})
      res.send({
        code: 200,
        msg: '收藏成功'
      })
    }
    
  } else {
    await collectionModel.create({ user_id: user_id, video_id: data._id, thumbs_up_state: false, collection_state: true })
    let video = await videoModel.findOne({ _id: data._id })
    await videoModel.updateOne({_id:video._id},{video_collection:video.video_collection+1})
    res.send({
      code: 200,
      msg: '收藏成功'
    })
  }
})

// 关注
router.post('/post_guanzhu',short_checkAuth(ACCESS_KEY),async(req,res)=>{
  let data = req.body
  let user_id = req.claim._id
  let guanzhu = await followsModel.findOne({ user_id:user_id,followed_id:data._id })
  console.log(guanzhu);
  if (guanzhu) {
    await followsModel.deleteOne({user_id:user_id,followed_id:data._id})
    let user = await loginModel.findOne({_id:user_id})
    res.send({
        code: 200,
        msg: '取消关注成功'
      })
  }else{
    await followsModel.create({user_id:user_id,followed_id:data._id})
    res.send({
      code:200,
      msg:'关注成功'
    })
  }
})

// 搜索
router.post('/post_sousuo',short_checkAuth(ACCESS_KEY),async(req,res)=>{
  let name = req.body.name
  let Name = RegExp(name)
  let video = await videoModel.find({video_desc:Name}).populate('user_id')
  console.log(video);
  
  res.send({
    code: 200,
    msg: '搜索成功',
    video: video
  })
})


// 获取当前登录人员信息
router.get('/get_user',short_checkAuth(ACCESS_KEY),async(req,res)=>{
  let _id = req.claim._id
  let video= await videoModel.find({user_id:_id}).lean()  
  let user = await loginModel.findOne({_id:_id}).lean()
  let aa = await thumbs_upModel.find({user_id:_id ,thumbs_up_state:true})
  let dianzan = await videoModel.find({_id:{$in:aa.map(item=>item.video_id)}})  
  let guanzhu = await followsModel.find({user_id:_id})
  let fensi = await followsModel.find({followed_id:_id})
  user.my_like = dianzan
  user.my_video  = video
  user.my_guanzhu = guanzhu
  user.my_fensi = fensi
  res.send({
    code: 200,
    msg: '获取成功',
    user: user
  })
})






// 刷新token
router.get('/refresh_token', length_checkAuth(REFRESH_KEY), length_checkAuth(REFRESH_KEY), async (req, res) => {
  let claim = req.claim  // 获取token中payload的信息
  let payload = {
    _id: claim._id,
    authentic_name: claim.authentic_name,
  }
  let access_token = generateToken(payload, ACCESS_KEY, '1h')
  res.send({
    code: 2000,
    msg: '刷新成功',
    access_token: access_token
  })
})


module.exports = router;